<script setup>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getPurchaseListService,
  addPurchaseService,
  updatePurchaseService,
  deletePurchaseService,
  findPendingApprovalsService,
  approvePurchaseService
} from "@/api/purchase.js";

const purchases = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const purchaseForm = reactive({
  purchaseId: '',
  deviceId: '',
  quantity: '',
  unitPrice: '',
  totalAmount: '',
  purchaseDate: '',
  supplier: '',
  contractNumber: '',
  purchaserId: '',
  warrantyUntil: '',
  createdAt: ''
});
const searchForm = reactive({
  purchaseId: '',
  deviceId: '',
  supplier: ''
});
const dialogVisible = ref(false);
const dialogTitle = ref('新增采购记录');
const isEdit = ref(false);

// 获取采购记录
const getPurchases = async (params) => {
  try {
    const res = await findPendingApprovalsService(params);
    if (res.code === 200) {
      purchases.value = res.data.list || [];
      total.value = res.data.total || 0;
    }
  } catch (error) {
    console.error("获取采购记录失败:", error);
  }
};

// 初始化加载数据
getPurchases({
  ...searchForm,
  pageNum: currentPage.value,
  pageSize: pageSize.value
});

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getPurchases({
    ...searchForm,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
};

// 处理页面大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  getPurchases({
    ...searchForm,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
};

// 打开新增对话框
const openAddDialog = () => {
  Object.assign(purchaseForm, {
    purchaseId: '',
    deviceId: '',
    quantity: '',
    unitPrice: '',
    totalAmount: '',
    purchaseDate: '',
    supplier: '',
    contractNumber: '',
    purchaserId: '',
    warrantyUntil: '',
    createdAt: ''
  });
  dialogTitle.value = '新增采购记录';
  isEdit.value = false;
  dialogVisible.value = true;
};

// 添加采购记录
const addPurchase = async () => {
  try {
    const res = await addPurchaseService(purchaseForm);
    if (res.code === 200) {
      ElMessage.success('添加成功');
      dialogVisible.value = false;
      getPurchases({
        ...searchForm,
        pageNum: currentPage.value,
        pageSize: pageSize.value
      });
    }
  } catch (error) {
    console.error("添加采购记录失败:", error);
  }
};

// 审批采购记录
const approvePurchase = (row, status) => {
  ElMessageBox.confirm(
      status === 1 ? '确定要审批通过这条采购记录吗？' : '确定要审批不通过这条采购记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: status === 1 ? 'success' : 'warning',
      }
  ).then(async () => {
    try {
      const res = await approvePurchaseService({
        purchaseId: row.purchaseId,
        approvalStatus: status,
        approvalComment: status === 1 ? '审批通过' : '审批不通过'
      });
      if (res.code === 200) {
        ElMessage.success(status === 1 ? '审批通过成功' : '审批不通过成功');
        getPurchases({
          ...searchForm,
          pageNum: currentPage.value,
          pageSize: pageSize.value
        });
      }
    } catch (error) {
      console.error("审批采购记录失败:", error);
    }
  }).catch(() => {
    // 取消审批
  });
};

// 查询采购记录
const searchPurchases = () => {
  currentPage.value = 1;
  getPurchases({
    ...searchForm,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
};

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '';
  const date = new Date(cellValue);
  if (isNaN(date.getTime())) {
    return cellValue;
  }
  return date.toLocaleDateString();
};
</script>

<template>
  <el-text class="mx-1" style="font-size: 1.25rem">采购记录</el-text>

  <!-- 查询表单 -->
  <el-form :inline="true" @submit.prevent>
    <el-form-item label="采购编号">
      <el-input v-model="searchForm.purchaseId" placeholder="请输入采购编号"></el-input>
    </el-form-item>
    <el-form-item label="设备编号">
      <el-input v-model="searchForm.deviceId" placeholder="请输入设备编号"></el-input>
    </el-form-item>
    <el-form-item label="供应商">
      <el-input v-model="searchForm.supplier" placeholder="请输入供应商"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="searchPurchases">查询</el-button>
    </el-form-item>
    <el-form-item>
      <el-button type="success" @click="openAddDialog">新增</el-button>
    </el-form-item>
  </el-form>

  <!-- 采购记录表格 -->
  <el-table :data="purchases" style="width: 100%">
    <el-table-column prop="purchaseId" label="采购编号" width="95"/>
    <el-table-column prop="deviceId" label="设备编号" width="95"/>
    <el-table-column prop="quantity" label="采购数量" width="95"/>
    <el-table-column prop="unitPrice" label="单价" width="95"/>
    <el-table-column prop="totalAmount" label="总金额" width="95"/>
    <el-table-column label="采购日期" width="95">
      <template #default="scope">
        {{ formatDate(scope.row, null, scope.row.purchaseDate) }}
      </template>
    </el-table-column>
    <el-table-column prop="supplier" label="供应商" width="95"/>
    <el-table-column prop="contractNumber" label="合同编号" width="95"/>
    <el-table-column prop="purchaserId" label="采购人ID" width="95"/>
    <el-table-column prop="approverName" label="审批人" width="95"/>
<!--    <el-table-column prop="approvalDate" label="审批日期" width="95"/>-->
<!--    <el-table-column prop="approvalComment" label="审批备注" width="95"/>-->
    <el-table-column label="保修截止日期" width="95">
      <template #default="scope">
        {{ formatDate(scope.row, null, scope.row.warrantyUntil) }}
      </template>
    </el-table-column>
    <el-table-column label="创建时间" width="95">
      <template #default="scope">
        {{ formatDate(scope.row, null, scope.row.createdAt) }}
      </template>
    </el-table-column>
    <el-table-column label="审批状态" width="95">
      <template #default="scope">
        <el-tag v-if="scope.row.approvalStatus === '1'" type="success">已通过</el-tag>
        <el-tag v-else-if="scope.row.approvalStatus === '0'" type="danger">未通过</el-tag>
        <el-tag v-else type="warning">未审批</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="120">
      <template #default="scope">
        <el-button type="primary" size="small" @click="approvePurchase(scope.row, 1)">审批通过</el-button>
        <el-button type="danger" size="small" @click="approvePurchase(scope.row, 0)">审批不通过</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <div class="demo-pagination-block">
    <div class="demonstration">页码</div>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 30, 50, 100]"
        :total="total"
        layout="sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 新增对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form :model="purchaseForm" label-width="100px">
      <el-form-item label="设备编号">
        <el-input v-model="purchaseForm.deviceId"></el-input>
      </el-form-item>
      <el-form-item label="采购数量">
        <el-input v-model="purchaseForm.quantity"></el-input>
      </el-form-item>
      <el-form-item label="单价">
        <el-input v-model="purchaseForm.unitPrice"></el-input>
      </el-form-item>
      <el-form-item label="总金额">
        <el-input v-model="purchaseForm.totalAmount"></el-input>
      </el-form-item>
      <el-form-item label="采购日期">
        <el-date-picker v-model="purchaseForm.purchaseDate" type="date" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
      <el-form-item label="供应商">
        <el-input v-model="purchaseForm.supplier"></el-input>
      </el-form-item>
      <el-form-item label="合同编号">
        <el-input v-model="purchaseForm.contractNumber"></el-input>
      </el-form-item>
      <el-form-item label="采购人ID">
        <el-input v-model="purchaseForm.purchaserId"></el-input>
      </el-form-item>
      <el-form-item label="保修截止日期">
        <el-date-picker v-model="purchaseForm.warrantyUntil" type="date" format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"></el-date-picker>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="addPurchase()">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.demonstration {
  margin-bottom: 10px;
}
</style>
